package com.ideabove.adapter;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;

import com.ideabove.network.NetWorkManager;
import com.ideabove.radio.MainActivity;
import com.ideabove.radio.R;
import com.ideabove.radio.module.ModuleAbs;
import com.ideabove.util.ConnectThread;
import com.ideabove.data.Folder;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.PorterDuff.Mode;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

public class FolderEditAdapter extends BaseAdapter
{

	private List<Folder> mList;
	private LayoutInflater mInflater;  
	private MainActivity activity;

	public FolderEditAdapter(Context c , ArrayList<Folder> arrays, MainActivity activty){
		this.mInflater = LayoutInflater.from(c);
		this.mList = arrays;
//		this.context = c;
		this.activity = activty;
	}

	int index = 0;

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		Folder folder = mList.get(position);
		
		if(convertView == null)
		{
			convertView = mInflater.inflate(R.layout.row_folder_edit, null);								
		}
		
		if("0".equals(folder.getType())){ // like folder
			ImageView folder_img = (ImageView) convertView.findViewById(R.id.folder_img);
			folder_img.setImageResource(R.drawable.img_like);
			folder_img.setEnabled(false);			
			folder_img.setPadding(10, 2, 2, 2);
			folder_img.setColorFilter(0xaa111111,Mode.SRC_OVER);
			
			EditText folder_name = (EditText) convertView.findViewById(R.id.folder_name);
			folder_name.setBackgroundColor(0);
			folder_name.setEnabled(false);
			
			
			FrameLayout folder_remove_btn_wrap = (FrameLayout) convertView.findViewById(R.id.folder_remove_btn_wrap);
			folder_remove_btn_wrap.setVisibility(View.GONE);
			
			
			
		}else if("1".equals(folder.getType())){ // basic folder
			ImageView folder_img = (ImageView) convertView.findViewById(R.id.folder_img);
			folder_img.setImageResource(R.drawable.img_lp);
			folder_img.setPadding(0, 0, 0, 0);
			folder_img.setColorFilter(0x00000000,Mode.SRC_OVER);
			
			EditText folder_name = (EditText) convertView.findViewById(R.id.folder_name);
			folder_name.setBackgroundColor(0x28282828);
			folder_name.setEnabled(true);			
			
			FrameLayout folder_remove_btn_wrap = (FrameLayout) convertView.findViewById(R.id.folder_remove_btn_wrap);
			folder_remove_btn_wrap.setVisibility(View.GONE);			
			
		}else{ // normal folder
			ImageView folder_img = (ImageView) convertView.findViewById(R.id.folder_img);
			folder_img.setImageResource(R.drawable.img_lp);
			folder_img.setPadding(0, 0, 0, 0);
			folder_img.setColorFilter(0x00000000,Mode.SRC_OVER);
			
			EditText folder_name = (EditText) convertView.findViewById(R.id.folder_name);
			folder_name.setBackgroundColor(0x28282828);
			folder_name.setEnabled(true);	
			folder_name.setImeActionLabel("변경", KeyEvent.KEYCODE_ENTER);
			
			folder_name.setOnEditorActionListener(new TextView.OnEditorActionListener() {
				
				@Override
				public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
					ModuleAbs.showProgressDialog(activity, "", "잠시만 기다려주세요...");
					final String folderName = v.getText().toString();
					final TextView tempView = v;
					
					int timeout = 3;
					new ConnectThread(timeout).setCallback(new ConnectThread.Callback() {
						
						@Override
						public void fail(Object result) {
							// TODO Auto-generated method stub
							ModuleAbs.hideProgressDialog();
							AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
							ab.setMessage("네트워크가 원활하지 않습니다.\n다시 시도해주세요.");					
							ab.setPositiveButton("ok", null);  
							ab.show();
						}
						
						@Override
						public void sucess(Object result){
							ModuleAbs.hideProgressDialog();
							AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
							ab.setMessage("폴더명이 변경되었습니다.");					
							ab.setPositiveButton("ok", null);  
							ab.show();							
						}
						
						@Override
						public void threadProcess(ConnectThread resultset) throws Exception {
							// TODO Auto-generated method stub					
							HttpClient client = NetWorkManager.getHttpConnection();    
							HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000);					

							HttpPost post = new HttpPost("http://14.63.217.155/radio_bonosound/editFolder.php");
							
//							a. uId:유저ID
//							b. fId:폴더ID
//							c. fTitle : 변경될 폴더 
//							-Response
//							    1. type : plain ( 0 : 실패, 1 : 성공 ) 
							
							String buserId = activity.facebookMd.getBonoUserId();	
							String folderId = tempView.getTag().toString();
							
							if(TextUtils.isEmpty(buserId) 
									|| TextUtils.isEmpty(folderId) || TextUtils.isEmpty(folderName)){
								throw new Exception("parameter error");
							}							
							
							List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
							params.add(new BasicNameValuePair("uId", buserId));
							params.add(new BasicNameValuePair("fId", folderId));
							params.add(new BasicNameValuePair("fTitle", folderName));
							
//							Log.e("#########request", "########" + post.getURI().toURL());
							
							UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
							post.setEntity(ent);
							HttpResponse responsePOST = client.execute(post);  

							InputStream in = responsePOST.getEntity().getContent();
							BufferedReader reader = new BufferedReader(new InputStreamReader(in));
							StringBuilder str = new StringBuilder();
							String line = null;
							while((line = reader.readLine()) != null)
							{					
								str.append(line);
							}
							in.close();					
//							String jsonStr = str.toString();
//							Log.e("#########result", "########" + jsonStr);
							
							
						}
					}).start(); 
					
					
					return false;
				}
			});
			
			FrameLayout folder_remove_btn_wrap = (FrameLayout) convertView.findViewById(R.id.folder_remove_btn_wrap);
			folder_remove_btn_wrap.setVisibility(View.VISIBLE);
			
			
			ImageView folder_remove_btn = (ImageView)convertView.findViewById(R.id.folder_remove_btn);
			folder_remove_btn.setTag(folder.getFolder_id());
			folder_remove_btn.setOnTouchListener(new View.OnTouchListener() {
				
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					ImageView view = (ImageView)v;
					if(event.getAction() == MotionEvent.ACTION_DOWN){
						view.setPadding(2, 2, 2, 2);
						view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
					}else if(event.getAction() == MotionEvent.ACTION_UP){
						final View vvv = v;						
						// 폴더이름 추가 다이얼로그
						String title = "삭제";
						AlertDialog.Builder aDialog = new AlertDialog.Builder(activity);
						aDialog.setTitle(title);	
						aDialog.setMessage("폴더안에 곡들이 삭제됩니다.\n삭제 하시겠습니까?");
						aDialog.setPositiveButton("삭제", new DialogInterface.OnClickListener() {
							 public void onClick(DialogInterface dialog, int which) {
								 String folderId = vvv.getTag().toString();
								 activity.folderEditMd.requestFolderRemove(folderId);
							 }
						});
						aDialog.setNegativeButton("취소", new DialogInterface.OnClickListener() {
							 public void onClick(DialogInterface dialog, int which) {
							 }
						});
						aDialog.show();
						
						view.setPadding(0, 0, 0, 0);
						view.setColorFilter(0x00000000, Mode.SRC_OVER);
					}else{
						view.setPadding(0, 0, 0, 0);
						view.setColorFilter(0x00000000, Mode.SRC_OVER);
					}
					return true;
				}
			});
		}
		
		EditText content = (EditText) convertView.findViewById(R.id.folder_name);
		content.setTag(folder.getFolder_id());
		content.setText(folder.getTitle());

		return convertView;
	}



	@Override
	public int getCount() {
		return mList.size();
	}
	@Override
	public Folder getItem(int position) {
		return mList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

}
